package com.swak.sit.objects;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.swak.sit.Sit;
import com.swak.utils.Bytes;
import com.swak.utils.Chars;
import com.swak.utils.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * Hash.
 * 
 * @author 618lf
 */
@Slf4j
public class Hash {

	public static String hashObject(byte[] fileContents) {
		return hashObject(fileContents, Sit.BLOB);
	}

	/**
	 * get hash of file content and create it with type describe.
	 * type could be: blob, tree, commit
	 */
	public static String hashObject(byte[] fileContents, String type) {
		byte[] targetFileContents = Bytes.concat(StringUtils.getBytesUtf8(type), Chars.toByteArray(Sit.NULL_CHAR),
				fileContents);
		byte[] digest = new byte[0];
		try {
			digest = MessageDigest.getInstance(Sit.HASH_ALGORITHM).digest(targetFileContents);
		} catch (NoSuchAlgorithmException e) {
			log.error("no such algorithm ");
		}

		// convert digest bytes to hex string
		String objectId = new BigInteger(1, digest).toString(16);
		log.info("objectId with {} type is {}", type, objectId);
		// create file with file name as object id
		return objectId;
	}
}
